package com.road2trip.datastore;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.datastore.Key;
import com.road2trip.datastore.Place.PlaceKey;
import com.road2trip.datastore.Place.PlaceType;

public final class PlaceDAO {

	private PlaceDAO() {
	}

	private static Boolean makePersistent(Place place) {
		return PMF.makePersistent(place);
	}

	public static Boolean makePersistent(Place place, Key parentID) {
		// place.setParent(parentID);
		return PlaceDAO.makePersistent(place);
	}

	public static Place byKey(PlaceKey key) {

		PersistenceManager pm = PMF.getPM();
		Query query = pm.newQuery(Place.class);
		query.setFilter("key.name == " + key.getName());
		query.setFilter("language == " + key.getLanguage());
		Place result = null;
		try {
			List<Place> results = (List<Place>) query.execute();
			if (results.size() == 1) {
				result = results.get(0);
			}
		} catch (Exception e) {
		} finally {
			pm.close();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	public static List<Place> getCountries() {
		Query query = PMF.getPM().newQuery(Place.class);
		query.setFilter("type == placeType");
		query.setOrdering("localizedName asc");
		query.declareParameters("Placetype placeType");

		List<Place> results = (List<Place>) query.execute(PlaceType.COUNTRY);
		return results;
	}

	public static Place getPlace(Place in) {

		// @TODO
		// http://code.google.com/apis/maps/documentation/geocoding/index.html
		// @TODO : use google translate to ensure palce name is OK?

		// search for the given place
		Place result = byKey(in.getKey());

		if (result == null) { // nothing found
			PersistenceManager pm = PMF.getPM();

			if (in.getKey().getLanguage() != "en") { // not in english : have a
														// look at the english
														// version
				PlaceKey enPlaceKey = new PlaceKey(in.getKey().getName(), "en");
				Place enPlace = byKey(enPlaceKey);
				if (enPlace == null) { // it really doesn't exist : first create
										// the english one
					enPlace = new Place(enPlaceKey);
					enPlace.setParent(in.getParent());
					enPlace.setType(in.getType());
					// @TODO : move place "type" to the key ??
					pm.makePersistent(enPlace);
				}
			}
			// here we have a english place, either because it exist or because
			// we have created it

			pm.makePersistent(in);
			result = in;
		}

		return result;
	}

}
